package com.witker.common.base;

import com.alibaba.fastjson.JSON;
import com.witker.common.ContextArgument;
import com.witker.common.DataPage;
import com.witker.common.StatusType;
import com.witker.common.util.NoneTypeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 视图控制器的父类
 * Created by BOCAI on 2018/9/15 20:23.
 */
public abstract class ModelSupport<Service extends ModuleService, T> extends ModelBase {

    /**
     * 业务控制器
     */
    @Autowired
    protected Service service;

    /**
     * 添加信息
     * @param jsonStr 保存信息的json
     * @return 返回结果对象
     */
    @RequestMapping("/add")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public Object add(@RequestBody String jsonStr){
        int code = StatusType.DEFAULT;
        T bean = this.parseObject(jsonStr, this.getClass());

        if ( service.save(bean) ) {
            code = StatusType.SUCCESS;
        }

        return this.getResult(code);
    }

    /**
     * 删除信息
     * @param ids id集合
     * @return 返回结果对象
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(@RequestBody List<String> ids){
        int code = StatusType.DEFAULT;

        if (NoneTypeUtil.isNullOrEmpty(ids)) {
            return this.getResult(code);
        }
        if (service.removeByIds(ids)) {
            code = StatusType.SUCCESS;
        }

        return this.getResult(code);
    }

    /**
     * 修改信息
     * @param jsonStr 保存信息的json
     * @return 返回结果对象
     */
    @RequestMapping("/modify")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public Object modify(@RequestBody String jsonStr){
        int code = StatusType.DEFAULT;
        T bean = this.parseObject(jsonStr, this.getClass());

        if ( service.updateById(bean) ){
            code = StatusType.SUCCESS;
        }

        return this.getResult(code);
    }

    /**
     * 查询信息
     * @param jsonStr 保存信息的json
     * @return 返回结果对象
     */
    @RequestMapping("/list")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public Object List(@RequestBody String jsonStr, DataPage dataPage, String orderBy){
        T bean = this.parseObject(jsonStr, this.getClass());
        List<T> beans =  service.beans(bean,dataPage,true, orderBy);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put(ContextArgument.GRID, beans);
        resultMap.put(ContextArgument.DATAPAGE, dataPage);
        return this.getResult(StatusType.SUCCESS, resultMap);
    }
}
